import os
import requests
import json
import jenkins
from utils.logger import logger


def DingSendMsg():
    try:
        # jenkins登录地址
        jenkins_url = "http://192.168.3.24:8080/jenkins/"
        # 获取jenkins对象
        server = jenkins.Jenkins(jenkins_url, username='zengao', password='Aa01114120')  # Jenkins登录名 ，密码
        # job名称
        job_name = "job/auto-testing/"
        # job的url地址
        job_url = jenkins_url + job_name
        # 获取最后一次构建地址
        # job_last_build_url = server.get_info(job_name)['lastBuild']['url']
        # 获取最后一次构建版本
        job_last_build_version = server.get_info(job_name)['lastBuild']['number']
        # 报告地址
        report_url = job_url + str(job_last_build_version) + '/allure'
        # 用msg存储prometheusData.txt文件中的内容
        msg = {}
        # 获取项目绝对路径
        path = os.path.dirname(os.path.dirname(__file__))
        # 打开prometheusData 获取需要发送的信息
        with open(path + r'\allure-report\export\prometheusData.txt', 'r') as f:
            for lines in f:
                for c in lines:
                    launch_name = lines.strip('\n').split(' ')[0]
                    num = lines.strip('\n').split(' ')[1]
                    msg.update({launch_name: num})
        retries_run = msg.get('launch_retries_run')  # 运行测试用例总数
        status_passed = msg.get('launch_status_passed')  # 测试用例通过数量
        status_failed = msg.get('launch_status_failed')  # 测试用例失败数量
        status_broken = msg.get('launch_status_broken')  # 测试用例中断数量
        # 这里要包含新增机器人时候“安全设置”里的关键字，这里是“自动化测试”
        cont = "自动化测试脚本执行完成：执行自动化脚本发现异常，请速度查看" + \
               "\n测试概述:" + \
               "\n运行测试用例总数:" + retries_run + \
               "\n通过测试用例数量:" + status_passed + \
               "\n失败测试用例数量:" + status_failed + \
               "\n中断测试用例数量:" + status_broken + \
               "\n构建地址:" + job_url + \
               "\n报告地址：\n" + report_url
        data = {
            "msgtype": "text",
            "text": {
                "content": cont
            },
            "at": {
                # @对象的电话号码
                "atMobiles": [13956968739],
                # 是否@所有人
                "isAtAll": False
            }
        }
        # url为钉钉机器人Webhook的值
        url = "https://oapi.dingtalk.com/robot/send?access_token=251e7384adcd20c6d4c432e798c534dc70c11c071d008af1dd88cfbf3117b090"
        headers = {
            'Content-Type': 'application/json'
        }
        requests.post(url=url, data=json.dumps(data), headers=headers)
    except Exception as e:
        logger.info('钉钉发送消息异常')
        return {'msg': '钉钉发送消息异常'}


if __name__ == '__main__':
    a = DingSendMsg()
    print(a)
    print('新增git测试')
    print('新增git测试1')